public class TTTGame
{
	/*
	 * need: structure to hold board state win condition check something to
	 * check moves
	 */
	public int[] state = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	

	static int[] winArray = { 7, 56, 73, 84, 146, 273, 292, 448 };
	GeneticPlayer p1;
	GeneticPlayer p2;
	boolean won = false;

	public TTTGame()
	{

	}

	public TTTGame(int[] inState)
	{
		state = inState;
	}

	public TTTGame(GeneticPlayer player1, GeneticPlayer player2)
	{
		p1 = player1;
		p2 = player2;
		// TODO Auto-generated constructor stub
	}

	public int[] getState()
	{
		return state;
	}
	
	public void setState(int[] inState)
	{
		state = inState;
	}

	public boolean canPlace(int n)
	{
		if (state[n] != 0)
			return false;
		else
			return true;
	}
	
	public boolean canPlaceAny()
	{
		for (int i = 0; i < 9; i++)
		{
			if (canPlace(i))
			{
				return true;
			}
		}
		return false;
	}

	public boolean placePiece(int place, int playerN)
	{
		if (!this.win(1) && !this.win(2))
		{
			if (canPlace(place))
			{
				state[place] = playerN;
				return true;
			}
			else
			{
				return false;
			}
		}
		else
			return false;
	}

	public int boardState()
	{
		// return a base 10 number representing the index of the current board
		// state
		int index = 0;
		// do a summation
		for (int i = 0; i < 9; i++)
		{
			index += state[i] * (Math.pow(3, i));
		}

		return index;
	}

	public boolean win(int n)
	{
		// check board state and determine if a win has happened
		int piecesNumber = 0;
		// build piecesNumber, a numerical representation of the board
		for (int i = 0; i < 9; i++)
		{
			if (state[i] == n)
			{
				piecesNumber += Math.pow(2, i);
			}
		}

		// try to find a win using the bitwise base 2 thing
		for (int i = 0; i < 8; i++)
		{
			if ((piecesNumber & winArray[i]) == winArray[i])
			{
				won = true;
				return true;
			}
		}
		// if a win is not found...
		return false;

	}

}
